import axios from 'axios'
import { Loading } from 'element-ui'
import { getToken } from '@/utils/auth'
import { paramsObj } from '@/utils/validate.js'
import { Message } from 'element-ui'

// 导出Excel公用方法
export function exportMethod(data) {
  const loading = Loading.service({
    lock: true,
    text: '数据导出中，请稍等...',
    background: 'rgba(255, 255, 255, 0.92)'
  })
  const baseURL = window.config.getAuthUrl().baseUrl
  const config = {
    method: data.method,
    url: window.config.getAuthUrl().baseUrl + data.url,
    responseType: 'blob',
    headers: {
      'content-type': 'application/vnd.ms-excel'
    }
  }
  data.params.token = getToken()
  if (data.method.toLowerCase() === 'get') {
    config.url = `${baseURL}${data.url}?${paramsObj(data.params)}`
  } else {
    config.headers['content-type'] = 'application/json'
    config.data = data.params
  }
  axios(config).then((res) => {
    console.log(res)
    if (res.status !== 1) {
      Message({
        message: '导出失败，' + res.msg + '！',
        type: 'error',
        duration: 1.5 * 1000
      })
      loading.close()
      return
    }
    var csvData = new Blob([res.data], { type: 'application/vnd.ms-excel;charset=utf-8' })
    const contentDisposition = res.headers['content-disposition']
    const fileName = window
      .decodeURI(contentDisposition.substring(contentDisposition.indexOf('=') + 1))
      .split('++')
      .join('')
      // for IE
    if (window.navigator && window.navigator.msSaveOrOpenBlob) {
      window.navigator.msSaveOrOpenBlob(csvData, fileName)
    } else {
      // for Non-IE (chrome, firefox etc.)
      var a = document.createElement('a')
      document.body.appendChild(a)
      a.style = 'display: none'
      var url = window.URL.createObjectURL(csvData)
      a.href = url
      a.download = fileName
      a.click()
      a.remove()
      window.URL.revokeObjectURL(url)
    }
    loading.close()
  }).catch((error) => {
    loading.close()
    console.log(error)
    Message({
      message: error.message || error.name,
      type: 'error',
      duration: 5 * 1000
    })
  })
}
